package com.example.guiguiapplicatio.fragment.FamilyArchives;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.guiguiapplicatio.api.GetFamilyarChivesApi;
import com.example.guiguiapplicatio.api.Interface.Api;
import com.example.guiguiapplicatio.api.Interface.GetFamilyarChivesCallback;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.FamilyarChivesList;
import com.example.guiguiapplicatio.Response.FamilyarChivesRecordList;
import com.example.guiguiapplicatio.fragment.FamilyArchives.adapter.FamilyArchivesAdapter;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class FamilyArchivesFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    EditText et_blood_pressure;
    EditText et_blood_pressure2;
    EditText et_blood_pressure3;
    EditText et_Family_number;
    RecyclerView recyclerView;
    Button confirm_the_contract2;
    Button comit_btu;
    ImageButton servic_back;
    private FamilyArchivesAdapter familyArchivesAdapter;
    private List<String> FamilyIdcardList = new ArrayList<>();
    private GetFamilyarChivesApi getFamilyarChivesApi;

    // TODO: Rename and change types of parameters
    private String idCard;
    private String HouseholdId;
    private Retrofit retrofit;
    private static OkHttpClient client = null;
    private Api api;
    RefreshLayout refreshLayout;
    Boolean refresh;
    FamilyarChivesList familyarChivesList;

    public FamilyArchivesFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BreakContinueFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FamilyArchivesFragment newInstance(String param1, String param2) {
        FamilyArchivesFragment fragment = new FamilyArchivesFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            idCard = getArguments().getString("idCard");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_total_detail_family, container, false);
        client = new OkHttpClient.Builder().
//                 readTimeout(30, TimeUnit.SECONDS).
//                writeTimeout(30, TimeUnit.SECONDS).
        connectTimeout(6, TimeUnit.SECONDS).build();//用于设置请求超时等限制时间

        retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(getString(R.string.api))
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        api = retrofit.create(Api.class);
        et_blood_pressure = root.findViewById(R.id.et_blood_pressure);
        et_blood_pressure2 = root.findViewById(R.id.et_blood_pressure2);
        et_blood_pressure3 = root.findViewById(R.id.et_blood_pressure3);
        comit_btu = root.findViewById(R.id.comit_btu);
        servic_back = root.findViewById(R.id.servic_back);
        confirm_the_contract2 = root.findViewById(R.id.confirm_the_contract2);
        recyclerView = root.findViewById(R.id.familyArchives_list);
        refreshLayout = (RefreshLayout)root.findViewById(R.id.flow_up_refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        getFamilyarChivesApi = new GetFamilyarChivesApi();
        getFamilyarChivesApi.setFamilyarChivesCallback(new GetFamilyarChivesCallback() {
            @Override
            public void onSuccess(ResponseBody<FamilyarChivesList> responseBody) {
                if (responseBody != null && responseBody.getData() != null) {
                    refresh = true;
                    familyarChivesList = responseBody.getData();
                    if (getActivity()!=null){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                HouseholdId = familyarChivesList.getHouseholdId();
                                et_blood_pressure.setText(familyarChivesList.getHouseholdName());
                                et_blood_pressure2.setText(familyarChivesList.getHouseholdSex());
                                et_blood_pressure3.setText(familyarChivesList.getHomeAddress());
                                LinearLayoutManager manager = new LinearLayoutManager(getContext());
                                recyclerView.setLayoutManager(manager);
                                familyArchivesAdapter = new FamilyArchivesAdapter(familyarChivesList.getFamilyMembers(), getContext(),api);
                                recyclerView.setAdapter(familyArchivesAdapter);
                            }
                        });
                    }

                }
            }

            @Override
            public void onFailure(String errorMessage) {
                refresh = false;
            }
        });
        getFamilyarChivesApi.performFamilyarChivesList(idCard);
        confirm_the_contract2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for(FamilyarChivesRecordList familyarChivesRecordList : familyarChivesList.getFamilyMembers()){
                    FamilyIdcardList.add(familyarChivesRecordList.getIdcard());
                }
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                bundle.putString("FamilyIdcardList", FamilyIdcardList.toString());
                bundle.putString("HouseholdId", HouseholdId);
                Navigation.findNavController(v).navigate(R.id.action_FamilyArchivesFragment_to_FamilyArchivesAddFragment,bundle);
            }
        });
        servic_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                Navigation.findNavController(v).navigate(R.id.action_FamilyArchivesFragment_to_recordDetailFragment,bundle);
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getFamilyarChivesApi.performFamilyarChivesList(idCard);
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                getFamilyarChivesApi.performFamilyarChivesList(idCard);
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
        comit_btu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                Navigation.findNavController(v).navigate(R.id.action_FamilyArchivesFragment_to_FamilySigningFragment,bundle);
            }
        });
        return root;
    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }
}
